package com.fk.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionController {
    @ExceptionHandler(value = SQLIntegrityConstraintViolationException.class)
    public R<String> resolveException(SQLIntegrityConstraintViolationException ex) {
        log.error("异常是：{}", ex.getMessage());
        if (ex.getMessage().contains("Duplicate entry")) {
            String[] strings = ex.getMessage().split(" ");
            String dupname = strings[2];

            return R.error(dupname + "已存在");
        }

        return R.error("未知错误");
    }

    @ExceptionHandler(value = CustomException.class)
    public R<String> resolveException(CustomException ex) {
        log.error("异常是：{}", ex.getMessage());
        return R.error(ex.getMessage());
    }

}
